<template>
  <div class="UserManage-container">
    <el-input
      placeholder="请输入内容"
      style="width:80%;"
      @change="SearchUsers"
      v-model="content"
    >
      <i slot="prefix" class="el-input__icon el-icon-search"></i>
    </el-input>
    <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
    <el-button
      style="margin-left:20px"
      type="warning"
      @click="OpenDeleteListDialog"
      >待删除列表</el-button
    >
    <div class="UserManage-table" v-if="userList.length">
      <el-table
        :data="userList"
        border
        @selection-change="handleSelectionChange"
        max-height="80%"
        :default-sort="{ prop: 'date', order: 'descending' }"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="创建日期" sortable width="180">
          <template slot-scope="scope">
            <svg-icon icon-class="date"></svg-icon>
            <span style="margin-left: 10px">{{
              scope.row.create_time | formatDate
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" width="80">
          <template slot-scope="scope">
            <el-popover trigger="click" placement="top">
              <p>姓名: {{ scope.row.name }}</p>
              <p>邮箱: {{ scope.row.email }}</p>
              <div>
                角色:
                <p v-if="roleList.length">
                  <el-tag v-for="r in roleList" :key="r.id">{{
                    r.role_name
                  }}</el-tag>
                </p>
                <p v-else>
                  暂无
                </p>
              </div>
              <div slot="reference" class="name-wrapper">
                <el-tag @click="getRoleListById(scope.row.id)" size="medium">{{
                  scope.row.name
                }}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="推荐码">
          <template slot-scope="scope">
            <span>{{ scope.row.referral_code }}</span>
          </template>
        </el-table-column>
        <el-table-column label="余额" width="70">
          <template slot-scope="scope">
            <span>{{ scope.row.coin }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最后登录IP" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.last_login_ip }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="warning"
              @click="distributeRole(scope.$index, scope.row)"
              >分配角色</el-button
            >
            <el-button
              size="mini"
              type="warning"
              @click="UserRecharge(scope.$index, scope.row)"
              >用户充值</el-button
            >
            <!-- <el-button size="mini"
                     type="info"
                     @click="handleEdit(scope.$index, scope.row)">更改密码</el-button> -->
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        small
        :limit="limit"
        :page-size="limit"
        :current-page="page"
        @current-change="pageChange"
        layout="prev, pager, next"
        :total="count"
      >
      </el-pagination>
    </div>
    <div v-else style="display:flex;justify-content:center">
      <img
        style="width:50%;margin:0 auto"
        src="@/assets/img/search-empty.png"
      />
    </div>
    <EditDialog
      :data="EditForm"
      dialogTitle="编辑用户"
      :visible="EditDialogVisible"
      @custom-confirm="EditConfirm"
      @custom-close="EditDialogClose"
    />
    <DistributeDialog
      @custom-confirm="distributeConfirm"
      @custom-cancel="ditributeDialogClose"
      dialogTitle="分配角色"
      :ids="roleList"
      type="role"
      :visible="distributeDialogVisible"
    />
    <el-dialog
      title="用户充值"
      @close="showRechargeDialogVisible = false"
      :visible.sync="showRechargeDialogVisible"
    >
      <el-form :model="rechargeForm" :rules="rechargeRules" ref="rechargeForm">
        <el-form-item label="支付类型" label-width="70px" prop="type">
          <el-input v-model="rechargeForm.type" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="订单号" label-width="70px" prop="order">
          <el-input v-model="rechargeForm.order" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="充值金额" label-width="70px" prop="num">
          <el-input-number
            v-model="rechargeForm.num"
            :precision="2"
            :step="0.1"
            :max="10000"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelRecharge">取 消</el-button>
        <el-button type="primary" @click="rechargeConfirm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 删除列表对话框 -->

    <DeleteListDialog
      :data="DeleteList"
      dialogTitle="删除用户列表"
      :pageSize="pageSize"
      :total="total"
      type="user"
      @custom-reload="getDeleteList"
      @current-page-change="DeleteListPageChange"
      :visible="DeleteListDialogVisible"
      @custom-close="DeleteListDialogClose"
    />
  </div>
</template>

<script>
import { encryptData } from '@/utils/encrypt'
import EditDialog from '@/components/Dialog/EditDialog'
import DistributeDialog from '@/components/Dialog/DistributeDialog'
import DeleteListDialog from '@/components/Dialog/DeleteListDialog'

export default {
  components: {
    EditDialog,
    DistributeDialog,
    DeleteListDialog
  },
  data() {
    return {
      limit: 10,
      page: 1,
      count: 0,
      // 用户列表
      userList: [],
      // 分配角色参数
      distributeForm: {
        role_ids: '',
        user_id: ''
      },
      // 充值表单
      rechargeForm: {
        num: 0,
        order: '',
        type: ''
      },
      content: '',
      // 编辑数据
      EditDialogVisible: false,
      formLabelWidth: '80px',
      // 分配角色对话框显示标志位
      distributeDialogVisible: false,
      EditForm: {},
      // 用户所有的角色列表
      roleList: [],
      selectedUsers: '',
      showRechargeDialogVisible: false,
      rechargeRules: {
        type: [
          { required: true, message: '请选择支付类型', trigger: 'change' }
        ],
        order: [{ required: true, message: '请输入订单号', trigger: 'change' }],
        num: [{ required: true, message: '请输入金额', trigger: 'change' }]
      },
      DeleteListDialogVisible: false,
      DeleteList: [], // 已删除列表
      // 删除列表分页信息
      pageSize: 3,
      currentPage: 1,
      total: null
    }
  },
  created() {
    // 获取用户列表
    this.$nextTick(() => {
      this.getUserList()
    })
  },
  mounted() {},
  methods: {
    pageChange(page) {
      this.page = page
      this.getUserList()
    },
    // 关闭已删除列表回调
    DeleteListDialogClose() {
      // 重新获取文章列表
      this.getUserList().then(() => {
        this.DeleteListDialogVisible = false
      })
    },
    // 打开待删除列表
    OpenDeleteListDialog() {
      this.getDeleteList()
        .then(() => {
          this.DeleteListDialogVisible = true
        })
        .catch(error => {
          console.log(error)
          this.$message.error('获取已删除列表失败')
        })
    },
    // 获取已删除列表
    async getDeleteList() {
      const { pageSize, currentPage } = this
      const res = await this.$API.user.getUserDeleteList(pageSize, currentPage)
      // 如果未获取到数据就退回一页重新获取数据
      if (res && !res.data) {
        if (currentPage <= 1) {
          return (this.DeleteList = [])
        } else {
          this.currentPage--
          this.getDeleteList()
        }
      }
      if (res.status == 200) {
        this.DeleteList = res.data.payload
        this.total = res.data.count
      } else {
        return this.$message.error('获取以删除列表失败')
      }
    },
    // 已删除列表页数改变
    DeleteListPageChange(currentPage) {
      this.currentPage = currentPage
      // 重新获取列表
      this.getDeleteList()
    },
    // 确认充值回调
    rechargeConfirm() {
      this.$refs.rechargeForm.validate(async valid => {
        if (!valid) return this.$message.error('参数不全')
        const formData = this.$qs.stringify(this.rechargeForm)
        const res = await this.$API.pay.UserRecharge(formData)
        if (res.status == 200) {
          this.$message.success('充值成功')
          // 重新获得用户列表
          this.getUserList()
          this.showRechargeDialogVisible = false
        }
      })
    },
    // 用户充值回调
    UserRecharge(id, user) {
      console.log(user)
      this.rechargeForm.usr_id = user.id
      this.showRechargeDialogVisible = true
    },
    // 取消充值
    cancelRecharge() {
      // 清空数据
      this.showRechargeDialogVisible = false
      this.rechargeForm = {}
    },
    // 获取角色列表
    async getRoleList() {
      const { rolePage, roleLimit } = this
      const res = await this.$API.role.getRoleList(roleLimit, rolePage)
      if (res.status == 200) {
        this.roleList = res.data.payload
        this.roleCount = res.data.count
      }
    },
    // 通过用户id获取用户的角色
    async getRoleListById(id) {
      const res = await this.$API.user.getRoleListById(id)
      // 如果不存在角色就将角色列表清空
      if (!res.data) return (this.roleList = [])
      if (res.status == 200) {
        this.roleList = res.data
      }
    },
    // 关闭分配角色窗口回调
    ditributeDialogClose() {
      this.distributeDialogVisible = false
    },
    // 获取用户列表
    async getUserList() {
      const { limit, page } = this
      const res = await this.$API.user.getUserList(limit, page)
      if (res.status == 200) {
        this.count = res.data.count
        this.userList = res.data.payload
      }
    },
    // 编辑用户
    handleEdit(id, user) {
      console.log(user)
      // 整理数据
      let datas = {
        id: user.id,
        email: user.email,
        password: '',
        name: user.name
      }
      // 获取数据
      this.EditForm = datas
      this.EditDialogVisible = true
    },
    // 删除用户
    handleDelete(id, user) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await this.$API.user.DeleteUser(user.id)
          if (res.status == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            // 初始化数据
            this.getUserList()
            this.content = ''
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 搜索用户
    async SearchUsers() {
      this.page = 1
      const { content, page, limit } = this
      console.log(content, page, limit)
      // 如果不存在搜索内容就获取全部
      if (!this.content) return this.getUserList()
      const res = await this.$API.user.SearchUsers(content, limit, page)
      // 如果不存在用户就显示空
      if (!res.data) this.userList = []
      console.log(res)
      if (res.status == 200) {
        this.userList = res.data.payload
        this.count = res.data.count
      }
    },
    // 关闭对话框
    EditDialogClose() {
      this.EditDialogVisible = false
    },
    // 确定编辑
    async EditConfirm(formData) {
      // 整理数据
      let { id, password, email, name } = formData
      // 获取公钥
      this.$store.dispatch('user/getPublicKey')
      const datas = {
        user_id: id,
        password: encryptData(password),
        email,
        name
      }
      console.log(encryptData(password))
      const res = await this.$API.user.EditUser(this.$qs.stringify(datas))
      if (res.status == 200) {
        this.$message.success('编辑成功')
        // 初始化数据
        this.EditDialogVisible = false
        this.content = ''

        this.getUserList()
        this.EditForm = {}
      } else {
        this.$message.error('编辑失败')
      }
    },
    // 分配角色
    async distributeRole(index, user) {
      // 获取当前分配的用户所有角色
      this.getRoleListById(user.id)
      this.distributeForm.user_id = user.id
      this.distributeDialogVisible = true
    },
    // 确认分配角色功能回调
    async distributeConfirm(role_ids) {
      // 整理数据
      this.distributeForm.role_ids = role_ids
      const res = await this.$API.user.bindRole(
        this.$qs.stringify(this.distributeForm)
      )
      if (res.status == 200) {
        this.$message.success('分配角色成功')
        // 初始化数据
        this.getUserList()
        this.content = ''
        this.distributeDialogVisible = false
      }
    },
    // 多选项切换时
    handleSelectionChange(selection) {
      this.selectedUsers = selection
    },
    // 批量删除
    handleBatchDelete() {
      if (this.selectedUsers.length === 0) {
        this.$message.warning('请选择要删除的文章')
        return
      }

      this.$confirm('此操作将永久删除选中的文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const userIds = this.selectedUsers.map(user => user.id)
          const formData = new FormData()
          formData.append('ids', userIds.join(','))
          const res = await this.$API.user.BatchDeleteUser(formData)
          if (res.status === 200) {
            this.$message.success('批量删除成功')
            this.getUserList()
            this.content = ''
            this.selectedUsers = []
          } else {
            this.$message.error('批量删除失败')
          }
        })
        .catch(() => {
          this.$message.info('已取消批量删除')
        })
    }
  }
}
</script>
<style scoped>
.UserManage-container {
  width: 100%;
  padding: 20px;
}
.UserManage-table {
  width: 100%;
  margin: 10px auto;
}
</style>